//
//  YHRefreshControl.swift
//  上拉下拉刷新框架
//
//  Created by key on 16/7/1.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

private let kscreenW = UIScreen.mainScreen().bounds.size.width

private let krefreshH: CGFloat = 50

enum YHRefreshType : Int {
    //默认 正常
    case Normal = 0
    //下拉中
    case Pulling = 1
    //刷新中
    case Refreshing = 2
    
}

class YHRefreshControl: UIControl {

    //创建全局被监听者
    private var scroll: UIScrollView?
    
    
    //MARK: - 当前状态
    private var refreshType: YHRefreshType = .Normal{
        
        didSet{
         
            switch refreshType {
                
            case .Normal:
                
                self.label.text = "正常"
                //当处于默认状态是 设置内边距
                //判断 当前状态处于 刷新中时 才重新设置
                if oldValue == .Refreshing {
                
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scroll?.contentInset.top -= krefreshH
                    })

                }
                
            case .Pulling:
                
                self.label.text = "下拉中"
            case .Refreshing:
                
                self.label.text = "刷新中"
                //设置内边距 动画效果
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    //设置内边距Top
                    self.scroll?.contentInset.top += krefreshH
                    
                    }, completion: { (_) -> Void in
                        
                        //发送通知 ValueChanged 改变
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                        
                        
                })
            }
        }
    }
    
    //MARK: - 懒加载文字控件
    private lazy var label: UILabel = {
       
        let leb = UILabel()
        
        leb.text = "正常"
        
        leb.textColor = UIColor.whiteColor()
        
        leb.font = UIFont.systemFontOfSize(16)
        
        leb.textAlignment = .Center

        return leb
        
    }()
    
    //MARK: - 入口
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -krefreshH, width: kscreenW, height: krefreshH))
        
        //设置自身背景颜色
        backgroundColor = UIColor.orangeColor()
        
        //设置UI
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI
    func setupUI() {
        
        //添加label
        addSubview(label)
    }
    
    
    
    //MARK: - 约束子控件完成 
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //约束label
        label.frame = CGRect(x: 0, y: 0, width: kscreenW, height: krefreshH)
        
    }
    
    
    //MARK: - 获取本控件的父控件
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        
        //判断父控件类型
        guard let scroll = newSuperview as? UIScrollView else {
         
            //不是UIScrollView 直接返回
            return
        }
        
        //是UIScrollView
        //记录当前被监听者
        self.scroll = scroll
        
        //KVO
        //注册监听者
        //被监听对象 添加监听者  scroll 被监听者
        //参数一 监听者
        //参数二 监听的属性 要监听什么
        //参数三 属性的变化
        //参数四 nil 不明白
        scroll.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
    }
    
    //MARK: - 监听到指定被监听者属性的变化 响应
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //获取被监听者的偏移量 
        let offsetY = self.scroll?.contentOffset.y
        
        let insetTop = self.scroll?.contentInset.top
        //判断被监听者 处于那种状态 是否是 被拖拽中
        if  scroll!.dragging {
//            print("被拖拽中")
            //判断 偏移量
            if offsetY >= -insetTop! - krefreshH && refreshType == .Pulling {
                refreshType = .Normal
                
            }else if offsetY < -insetTop! - krefreshH && refreshType == .Normal {
                refreshType = .Pulling
                
            }
            
        }else{
//            print("松手")
            
            if refreshType == .Pulling {
                //设置状态
                refreshType = .Refreshing
            }
            
        }
        
        
    }
    
    
    
    //MARK: - 关闭动画
    func endRefreshing() {
        
        refreshType = .Normal
        
    }
    
    
    //KVO 释放监听
    deinit {
        
        self.scroll?.removeObserver(self, forKeyPath: "contentOffset")
        
    }

    

}
